import 'dart:math';

import 'package:fluro/fluro.dart';
import 'package:flutter/material.dart';
import 'package:flutter_picker/flutter_picker.dart';
import 'package:hbtrans_flutter/beans/classdetail_bean.dart';
import 'package:hbtrans_flutter/utils/fluro.dart';
import 'package:hbtrans_flutter/utils/mydio.dart';

import '../apis.dart';
import '../const.dart';
import '../routes.dart';

class ClassLogin extends StatefulWidget {
  @override
  _ClassLoginState createState() => _ClassLoginState();
}

class _ClassLoginState extends State<ClassLogin> {
  var loadingDialog;
  var uuid = '';
  var classes = ['A1', 'A2', 'A3', 'B1', 'B2', 'C1', 'C2', 'C3', 'C4', 'C5'];
  var traintype = 'A1';

  TextEditingController _phoneController =
      TextEditingController.fromValue(TextEditingValue(text: ''));
  TextEditingController _cardController =
      TextEditingController.fromValue(TextEditingValue(text: ''));
  TextEditingController _codeController =
      TextEditingController.fromValue(TextEditingValue(text: ''));
  TextEditingController _typeController;
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();

  _maleRedomId() {
    String alphabet = 'QWERTYUIOPASDFGHJKLZXCVBNM1234567890';
    int strlenght = 16;
    String left = '';
    for (var i = 0; i < strlenght; i++) {
      left = left + alphabet[Random().nextInt(alphabet.length)];
    }
    return left;
  }

  _showPickerIcons(BuildContext context) {
    Picker(
      adapter: PickerDataAdapter(data: _setPickerItems()),
      title: Text('请选择'),
      cancelText: '取消',
      confirmText: '确定',
      selectedTextStyle: TextStyle(color: Colors.blue),
      onConfirm: (Picker picker, List value) {
        setState(() {
          traintype = classes[value[0]];
          _typeController = TextEditingController.fromValue(
              TextEditingValue(text: traintype));
        });
        print(traintype);
      },
    ).show(_scaffoldKey.currentState);
  }

  _setPickerItems() {
    List<PickerItem<dynamic>> pickerItems = List();
    for (String s in classes) {
      pickerItems.add(PickerItem(
          value: Icons.add,
          text: Text(s,
              style: TextStyle(color: const Color(0xff333333), fontSize: 16))));
    }
    return pickerItems;
  }

  _login() async {
    Map data = Map<String, dynamic>();
    if (Const.isDebug) {
      data["phone"] = '17378999117';
      data["idCard"] = '510524198401114717';
      data["traintype"] = 'C1';
      data["imageCode"] = _codeController.text;
      data["key"] = uuid;
    } else {
      data["phone"] = _phoneController.text;
      data["idCard"] = _cardController.text;
      data["traintype"] = traintype;
      data["imageCode"] = _codeController.text;
      data["key"] = uuid;
    }

    MyDio.getInstance(url: Const.TRANS_SERVER_PATH).get(Apis.classLogin,
        (data) {
      print(data);
      if (loadingDialog != null) {
        loadingDialog = null;
        Navigator.pop(context);
      }
      setState(() {
        var bean = ClassdetailBean.fromJson(data);
        String content = FluroConvertUtils.object2string(bean);
        String route =
            '${Routes.classDetail}?content=${FluroConvertUtils.fluroCnParamsEncode(content)}';
        Routes.router.navigateTo(context, route,
            replace: true, transition: TransitionType.fadeIn);
      });
    }, params: data);
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    _typeController =
        TextEditingController.fromValue(TextEditingValue(text: traintype));

    setState(() {
      uuid = _maleRedomId();
      print(uuid);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: _scaffoldKey,
      appBar: AppBar(
        backgroundColor: const Color(0xff23AFDC),
        elevation: 0,
        title: Text('学时查询'),
        centerTitle: true,
      ),
      body: ListView(
        padding: EdgeInsets.fromLTRB(38, 50, 38, 0),
        children: <Widget>[
          Center(
              child: Text(
            '学员培训有效学时查询系统',
            style: TextStyle(color: const Color(0xff23AFDC), fontSize: 14),
          )),
          SizedBox(
            height: 46,
          ),
          MyTextField(
            controller: _phoneController,
            imageSrc: 'images/ic_base_info_phone.png',
            hintText: '请输入手机号',
          ),
          SizedBox(
            height: 20,
          ),
          MyTextField(
            controller: _cardController,
            imageSrc: 'images/ic_card_id.png',
            hintText: '请输入身份证号',
          ),
          SizedBox(
            height: 20,
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              Expanded(
                child: GestureDetector(
                  onTap: () {
                    _showPickerIcons(context);
                  },
                  child: Stack(
                    children: <Widget>[
                      MyTextField(
                        readOnly: true,
                        controller: _typeController,
                        imageSrc: 'images/ic_type.png',
                      ),
                      SizedBox(
                        width: 300,
                        height: 40,
                        child: Card(
                          elevation: 0,
                          color: Colors.transparent,
                        ),
                      ),
                    ],
                  ),
                ),
              ),
              Image.asset(
                'images/ic_triangle.png',
                width: 24,
                height: 24,
                fit: BoxFit.fill,
              )
            ],
          ),
          SizedBox(
            height: 20,
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              Expanded(
                child: MyTextField(
                  controller: _codeController,
                  imageSrc: 'images/ic_verify.png',
                  hintText: '请输入验证码',
                ),
              ),
              GestureDetector(
                onTap: () {
                  setState(() {
                    uuid = _maleRedomId();
                    print(uuid);
                  });
                },
                child: uuid == ''
                    ? Image.asset('')
                    : Image.network(
                        '${Const.TRANS_SERVER_PATH}/image/getCode?key=$uuid'),
              ),
            ],
          ),
          SizedBox(
            height: 30,
          ),
          MaterialButton(
            height: 35,
            minWidth: MediaQuery.of(context).size.width,
            elevation: 0,
            onPressed: () {
              _login();
            },
            child: Text(
              "查询",
              style: TextStyle(color: Colors.white, fontSize: 16),
            ),
            color: Color(0xff23AFDC),
            shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.all(Radius.circular(20))),
          )
        ],
      ),
    );
  }
}

class MyTextField extends StatelessWidget {
  final imageSrc;
  final controller;
  final hintText;
  final readOnly;

  const MyTextField(
      {Key key, this.imageSrc, this.controller, this.hintText, this.readOnly})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return TextFormField(
      readOnly: readOnly == null ? false : readOnly,
      keyboardType: TextInputType.number,
      controller: controller,
      style: TextStyle(fontSize: 14, color: Color(0xff999999)),
      textCapitalization: TextCapitalization.words,
      decoration: InputDecoration(
        focusedBorder: UnderlineInputBorder(
            borderSide: BorderSide(color: Color(0xffE4E4E4))),
        enabledBorder: UnderlineInputBorder(
            borderSide: BorderSide(color: Color(0xffE4E4E4))),
        fillColor: Colors.transparent,
        filled: true,
        icon: Image.asset(
          imageSrc,
          height: 24,
          width: 24,
          fit: BoxFit.fill,
        ),
        hintText: hintText,
        hintStyle: TextStyle(fontSize: 14, color: Color(0xff999999)),
      ),
    );
  }
}
